package nowcoder.offer;

/**
 * 字符串转整数
 *
 * @author briarbear
 * @blog https://briarbear.github.io
 * @date 2018-08-28 19:16
 */
public class StrToInt {

    public int solution(String str){
        if (str == null || str.equals("")) return 0;
        char[] array = str.toCharArray();
        int len = array.length;
        int res = 0,carry = 1;
        for (int i = 1; i < len; i++) {
            if (isNumber(array[len-i])){
                res += (array[len-i] - '0') * carry;
                carry *= 10;
            }else
                return 0;
        }
        switch (array[0]){
            case '+':res *=1;break;
            case '-':res *= -1;break;
            default: if (isNumber(array[0])){
                res += (array[0]-'0')*carry;
                break;
            }else return 0;
        }

        return res;
    }

    public boolean isNumber(char c){
        if (c - '0' >=0 && '9' - c >=0)
            return true;
        return false;
    }

    public static void main(String[] args) {
        System.out.println(new StrToInt().solution("a2145646"));
    }
}
